package dao

import (
	"Im/global"
	"context"
	"fmt"
	"github.com/spf13/viper"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"log"
	"time"
)

// 初始化mongodb数据库链接
func InitMongoDB() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	dbUrl := fmt.Sprintf("mongodb://%s:%d", viper.GetString("mongoDb.address"), viper.GetInt("mongoDb.port"))
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(dbUrl))
	if err != nil {
		log.Println(err)
	}
	db := client.Database("IM")
	global.DB = db
}

// 初始化Mysql的链接
func InitMysql() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		viper.GetString("mysql.user"),
		viper.GetString("mysql.pwd"),
		viper.GetString("mysql.address"),
		viper.GetInt("mysql.port"),
		viper.GetString("mysql.database"))
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			//TablePrefix:   "f_",  // 表名前缀
			SingularTable: true, // 单数表名
			//NoLowerCase:   false, // 关闭小写转换
		},
	})
	global.SqlDb = db
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(viper.GetInt("mysql.maxIdleConn"))
	sqlDB.SetMaxOpenConns(viper.GetInt("mysql.maxOpenConn"))
	sqlDB.SetConnMaxLifetime(time.Hour)
	fmt.Println(db, err)

}
